package com.unis.service.system.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.StrUtil;
import com.unis.common.util.TemplateUtil;
import com.unis.common.util.TimeUtil;
import com.unis.dto.ResultDto;
import com.unis.pojo.Attachment;
import com.unis.service.system.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.service.impl.BaseServiceImpl;
import com.unis.mapper.system.DwDzzMapper;
import com.unis.model.system.DwDzz;
import com.unis.service.system.DwDzzService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see DwDzzService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-01-31
 */
@Service("dwDzzService")
public class DwDzzServiceImpl extends BaseServiceImpl implements DwDzzService {
    private static final Logger logger = LoggerFactory.getLogger(DwDzzServiceImpl.class);
    @Autowired
    private DwDzzMapper dwDzzMapper;
    @Autowired
    private AttachmentService attachmentService;

    /**
     * @see DwDzzService#insert(DwDzz dwDzz)
     */
    @Override
    public int insert(DwDzz dwDzz) throws Exception {
        if (dwDzz != null) {
            dwDzz.setPk(TemplateUtil.genUUID());
            //menu.setPk(getPk("seqName","jgdm","A"));
            UserInfo userInfo = this.getUserInfo();
            dwDzz.setLrdw(userInfo.getJgdm());
            dwDzz.setLrdwmc(userInfo.getJgmc());
            dwDzz.setLrr(userInfo.getXm());
            dwDzz.setLrrjh(userInfo.getJh());
            Date dbDate = this.getDbDate();
            dwDzz.setDzyear(TimeUtil.fmtDate(dbDate, "yyyy"));

            return dwDzzMapper.insertSelective(dwDzz);
        } else {
            logger.error("DwDzzServiceImpl.insert时dwDzz数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.insert时dwDzz数据为空。");
        }
    }

    /**
     * @see DwDzzService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("DwDzzServiceImpl.delete时pk为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.delete时pk为空。");
        } else {
            DwDzz dwDzz = this.queryDwDzzByPrimaryKey(pk);
            this.deleteMongo(dwDzz.getCxz());
//    		this.deleteMongo(dwDzz.getZfz());
            return dwDzzMapper.deleteByPrimaryKey(pk);
        }
    }

    private void deleteMongo(String mongoPk) {
        if (StringUtils.isBlank(mongoPk)) {
            return;
        }
        String[] mongo = mongoPk.split("/");
        Attachment attachment = new Attachment();
        attachment.setPk(mongo[2]);
        attachment.setCatalog(mongo[1]);
        attachment.setAttachmentDb(mongo[0]);
        attachmentService.remove(attachment);
    }

    /**
     * @see DwDzzService#updateByPrimaryKey(DwDzz dwDzz)
     */
    @Override
    public int updateByPrimaryKey(DwDzz dwDzz) throws Exception {
        if (dwDzz != null) {
            if (StringUtils.isBlank(dwDzz.getPk())) {
                logger.error("DwDzzServiceImpl.updateByPrimaryKey时dwDzz.Pk为空。");
                throw new AppRuntimeException("DwDzzServiceImpl.updateByPrimaryKey时dwDzz.Pk为空。");
            }
            UserInfo user = this.getUserInfo();
            dwDzz.setXgdw(user.getJgdm());
            dwDzz.setXgdwmc(user.getJgmc());
            dwDzz.setXgr(user.getXm());
            dwDzz.setXgrjh(user.getJh());
            dwDzz.setXgsj(this.getDbDate());
            return dwDzzMapper.updateByPrimaryKeySelective(dwDzz);
        } else {
            logger.error("DwDzzServiceImpl.updateByPrimaryKey时dwDzz数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.updateByPrimaryKey时dwDzz数据为空。");
        }
    }

    /**
     * @see DwDzzService#queryDwDzzByPrimaryKey(String pk)
     */
    @Override
    public DwDzz queryDwDzzByPrimaryKey(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("DwDzzServiceImpl.queryDwDzzByPrimaryKey时pk为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryDwDzzByPrimaryKey时pk为空。");
        } else {
            return dwDzzMapper.selectByPrimaryKey(pk);
        }
    }

    @Override
    public DwDzz queryDwDzzByDwdm(String dwdm) throws Exception {
        if (StringUtils.isBlank(dwdm)) {
            logger.error("DwDzzServiceImpl.queryDwDzzByDwdm时dwdm为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryDwDzzByDwdm时dwdm为空。");
        } else {
            return dwDzzMapper.queryDwDzzByDwdm(dwdm);
        }
    }


    /**
     * @see DwDzzService#queryAsObject(DwDzz dwDzz)
     */
    @Override
    public DwDzz queryAsObject(DwDzz dwDzz) throws Exception {
        if (dwDzz != null) {
            return dwDzzMapper.selectOne(dwDzz);
        } else {
            logger.error("DwDzzServiceImpl.queryAsObject时dwDzz数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryAsObject时dwDzz数据为空。");
        }
    }

    /**
     * @see DwDzzService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
        if (example != null) {
            return dwDzzMapper.selectCountByExample(example);
        } else {
            logger.error("DwDzzServiceImpl.queryCountByExample时example数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryCountByExample时example数据为空。");
        }
    }

    /**
     * @see DwDzzService#queryListByExample(Example example)
     */
    @Override
    public List<DwDzz> queryListByExample(Example example) throws Exception {
        if (example != null) {
            return dwDzzMapper.selectByExample(example);
        } else {
            logger.error("DwDzzServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see DwDzzService#queryPageInfoByExample(Example example, int pageNum, int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example, int pageNum, int pageSize) throws Exception {
        if (example != null) {
            PageHelper.startPage(pageNum, pageSize);
            return new PageInfo(dwDzzMapper.selectByExample(example));
        } else {
            logger.error("DwDzzServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see DwDzzService#queryListByPage(Map parmMap, int pageNum, int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws Exception {
        if (parmMap != null) {
            Example example = new Example(DwDzz.class);
            example.setOrderByClause("rksj DESC,pk asc");//设置排序
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("yxx", 1);//设置yxx=1
            //criteria设置
            // = --> andEqualTo(field,value)
            // like --> andLike(field,likeValue)；likeValue 包含‘%’
            // is null --> andIsNull(field)
            // is not null --> andIsNotNull(field)
            // <> --> andNotEqualTo(field)
            // > --> andGreaterThan(field,value)
            // >= --> andGreaterThanOrEqualTo(field,value)
            // < --> andLessThan(field,value)
            // <= --> andLessThanOrEqualTo(field,value)
            // in --> andIn(field,Iterable value)
            // not in --> andNotIn(field,Iterable value)
            // between --> andBetween(field,beginValue,endValue)
            // not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

            // or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

            /**
             *此方法请根据需要修改下方条件
             */
            //此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
            //生成条件中均为 and field = value
            //生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改

            boolean flag = false;
            if (parmMap.get("pk") != null && StringUtils.isNotBlank(parmMap.get("pk").toString())) {
                criteria.andEqualTo("pk", parmMap.get("pk").toString().trim());
                flag = true;
            }
            if (parmMap.get("dwdm") != null && StringUtils.isNotBlank(parmMap.get("dwdm").toString())) {
                criteria.andEqualTo("dwdm", parmMap.get("dwdm").toString().trim());
                flag = true;
            }
            if (parmMap.get("rksj") != null && StringUtils.isNotBlank(parmMap.get("rksj").toString())) {
                criteria.andEqualTo("rksj", parmMap.get("rksj").toString().trim());
                flag = true;
            }
            //一个条件都没有的时候给一个默认条件
            if (!flag) {
                criteria.andLike("dwdm", StrUtil.removeDmZeor(this.getUserInfo().getJgdm()) + "%");
            }
            PageInfo pageInfo = this.queryPageInfoByExample(example, pageNum, pageSize);
            ResultDto result = new ResultDto();
            result.setRows(pageInfo.getList());
            result.setPage(pageInfo.getPageNum());
            //result.setTotal(pageInfo.getPages());
            result.setTotal((int) pageInfo.getTotal());
            return result;
        } else {
            logger.error("DwDzzServiceImpl.queryListByPage时parmMap数据为空。");
            throw new AppRuntimeException("DwDzzServiceImpl.queryListByPage时parmMap数据为空。");
        }
    }
}
